<template>
    <div class="authority">
        <div class="gva-search-box">
            <el-form ref="searchForm" label-width="150" :inline="true"
            style="display: flex;flex-direction: column;align-items: center;">
                <div>
                    <el-form-item label="巡查类型">
                    <el-select v-model.number="searchInfo.type" placeholder="请选择" style="width: 300px;">
                        <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="任务名称">
                    <el-input v-model="searchInfo.name" placeholder="请输入" style="width: 300px;"/>
                </el-form-item>
                </div>
               <div>
                <el-form-item label="任务状态">
                    <el-select v-model.number="searchInfo.taskStatus" placeholder="请选择" style="width: 300px;">
                        <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="任务下达日期">
                    <el-date-picker v-model="searchInfo.time" type="daterange" range-separator="-"
                        start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                        style="width:300px" />
                </el-form-item>
               </div>
                <el-form-item>
                    <el-button type="primary" icon="search" @click="onSubmit">
                        查询
                    </el-button>
                    <el-button icon="refresh" @click="onReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="gva-table-box unit">
            <div class="gva-btn-list">
                <el-button type="primary" icon="plus" @click="addUnit">新增</el-button>
            </div>
            <div class="ant-alert-info">
                <el-popover placement="left-start" :width="350" trigger="click" transition='el-zoom-in-left'>
                    <div class="pop-content">
                        <div class="pop-title">自定义列</div>
                        <div class="check-list">
                            <el-checkbox-group v-model="checkedColumns" @change="handleColumnsChange">
                                <el-checkbox v-for="column in columns" :value="column" :label="column"></el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                    <template #reference>
                        <div class="anticon">
                            <el-icon size="16" color="#1890ff">
                                <Setting />
                            </el-icon>
                            <div style="margin-left: 2px;">自定义列</div>
                        </div>
                    </template>
                </el-popover>
            </div>
            <el-table :data="tableData" row-key="id">
                <el-table-column type="index" label="序号" width="100" />
                <el-table-column align="left" label="巡查类型" v-if="checkedColumns.includes('巡查类型')">
                    <template #default="scope">
                        <span>{{ scope.row.type == 1 ? '日常巡查' : '综合巡查' }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="任务名称" prop="name" show-overflow-tooltip
                    v-if="checkedColumns.includes('任务名称')"></el-table-column>
                <el-table-column align="left" label="巡查系统" v-if="checkedColumns.includes('巡查系统')" show-overflow-tooltip>
                    <template #default="scope">
                        {{scope.row.checkOptions.map(item => item.name).join(',')}}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="任务状态" prop="downloadTimes" v-if="checkedColumns.includes('任务状态')">
                    <template #default="scope">
                        <el-tag v-if="scope.row.taskStatus == 0">未开始</el-tag>
                        <el-tag v-if="scope.row.taskStatus == 1">进行中</el-tag>
                        <el-tag v-if="scope.row.taskStatus == 2">已结束</el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="任务下达日期" width="120" prop="name"
                    v-if="checkedColumns.includes('任务下达日期')">
                    <template #default="scope">
                        {{ formatTimestamps(scope.row.createdAt) }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="开始日期" prop="downloadTimes" v-if="checkedColumns.includes('开始日期')">
                    <template #default="scope">
                        {{ formatTimestamps(scope.row.start) }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="结束日期" prop="downloadTimes" v-if="checkedColumns.includes('结束日期')">
                    <template #default="scope">
                        {{ formatTimestamps(scope.row.end) }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="单位数量" prop="unitNums"
                    v-if="checkedColumns.includes('单位数量')"></el-table-column>
                <el-table-column align="left" label="已完成数" v-if="checkedColumns.includes('已完成数')">
                    <template #default="scope">
                        <span style="cursor: pointer;color: #3b82f6;" @click="showDialog3(scope.row, 1)">{{
                            scope.row.completeUnit ? scope.row.completeUnit.length : 0 }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="未完成数" v-if="checkedColumns.includes('未完成数')">
                    <template #default="scope">
                        <span style="cursor: pointer;color: #3b82f6;" @click="showDialog3(scope.row, 2)"> {{
                            scope.row.notCompleteUnit ? scope.row.notCompleteUnit.length : 0 }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" fixed="right" label="操作" min-width="140"
                    v-if="checkedColumns.includes('操作')">
                    <template #default="scope">
                        <el-button type="primary" link icon="edit" @click="editUnit(scope.row)" v-if="scope.row.completeUnit.length==0">
                            编辑
                        </el-button>
                        <el-button type="danger" link icon="delete" @click="delUnit(scope.row)" v-if="scope.row.completeUnit.length==0">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="gva-pagination">
                <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total"
                    layout="prev, pager, next" @current-change="handleCurrentChange" />
            </div>
        </div>
        <el-drawer v-model="dialogFormVisible" :size="1000" :before-close="handleClose" :show-close="false">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">{{ dialogTitle }}</span>
                    <div>
                        <el-button @click="closeDialog">取消</el-button>
                        <el-button type="primary" @click="enterDialog">确定</el-button>
                    </div>
                </div>
            </template>
            <el-form v-if="dialogFormVisible" ref="yyglForm" label-width="150" :model="form" :rules="rules">
                <el-form-item label="巡查类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择">
                        <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="任务名称" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="巡查单位" prop="unitIds">
                    <el-input v-model="form.units" placeholder="请选择" @click.native="openUnit"></el-input>
                </el-form-item>
                <el-form-item label="巡查时间" prop="time">
                    <el-date-picker v-model="form.time" type="daterange" range-separator="-" start-placeholder="开始时间"
                        end-placeholder="结束时间" format="YYYY-MM-DD" style="width:400px" />
                </el-form-item>
                <el-form-item label="巡查系统" prop="checkOptions" style="align-items: normal;">
                    <el-checkbox-group v-model="form.checkOptions">
                        <el-checkbox v-for="item in checkOptions" :value="item.id" :label="item.name"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
        </el-drawer>
        <el-drawer v-model="dialog2" :size="1200" :before-close="handleClose2" :show-close="false">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">选择单位</span>
                    <div>
                        <el-button @click="closeDialog2">取消</el-button>
                        <el-button @click="confirm2" type="primary">确定</el-button>
                    </div>
                </div>
            </template>
            <div class="flex">
                <div class="xz-box">
                    <div class="xz-list">
                        <div class="title" style="font-weight: bold;margin-bottom: 20px;">单位性质</div>
                        <div v-for="item in xzList" class="item" @click="xzChange(item.id)">{{ item.name }}</div>
                    </div>
                </div>
                <div class="unit-box">
                    <div class="top">
                        <div class="search">
                            <el-form :inline="true">
                                <el-form-item label="单位名称">
                                    <el-input v-model="unitForm.name"></el-input>
                                </el-form-item>
                                <el-form-item style="margin-right: 0;">
                                    <el-button type="primary" icon="search" @click="search">
                                        查询
                                    </el-button>
                                    <el-button icon="refresh" @click="unitReset">重置</el-button>
                                </el-form-item>
                            </el-form>
                        </div>
                    </div>
                    <el-table ref="unitTable" :data="unitData" border
                        @selection-change="handleSelectionChange" :row-key="rowKey">
                        <el-table-column type="selection" width="55" :reserve-selection="true"/>
                        <el-table-column align="left" label="单位名称" prop="name"></el-table-column>
                        <el-table-column align="left" label="单位地址" prop="address"></el-table-column>
                    </el-table>
                    <div class="gva-pagination">
                        <el-pagination v-model:current-page="unitPage" :page-size="unitPageSize" :total="unitTotal"
                            layout="prev, pager, next" @current-change="handleUnitChange" />
                    </div>
                </div>
                <div class="select-box">
                    <div class="title" style="font-weight: bold;margin-bottom: 20px;">已选择单位</div>
                    <div class="select-list" v-if="selectedUnit.length>0">
                        <div v-for="item in selectedUnit" class="item">{{ item.name }}</div>
                    </div>
                </div>
            </div>
        </el-drawer>
        <el-drawer v-model="dialog3" :size="1000" :before-close="handleClose3" :show-close="false"
            class="loudong-drawer">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">{{ statusTitle }}</span>
                    <div>
                        <el-button @click="closeDialog3">取消</el-button>
                    </div>
                </div>
            </template>
            <el-table :data="unitStatusData" row-key="id">
                <el-table-column align="left" label="单位名称" prop="unitName">
                </el-table-column>
                <el-table-column align="left" label="联系人" prop="contacts"></el-table-column>
                <el-table-column align="left" label="联系方式" prop="contactUs"></el-table-column>
            </el-table>
        </el-drawer>
    </div>
</template>
<script setup>
import {
    patrolTask,
    taskEdit,
    taskDelete,
    taskAdd,
    optionList
} from '@/api/yewuguanli'
import {
    unitLists
} from '@/api/unit'
import {
    getDyList
} from '@/api/xitongpeizhi'

import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { countdownEmits, ElMessage, ElMessageBox, useFormItem } from 'element-plus'
import { formatTimestamps } from '@/utils/format'
const { formItem } = useFormItem()

defineOptions({
    name: 'Yygl'
})
const appStore = useAppStore()
const form = ref({
    name: '',
    type: '',
    time: [],
    start: '',
    end: '',
    checkOptions: [],
    units: '',
    unitIds: ''
})

const searchInfo = ref({
    name: '',
    time: [],
    taskStart: '',
    taskEnd: '',
    taskStatus: '',
    type: ''
})

const typeList = ref([
    {
        name: '日常巡查',
        id: 1
    },
    {
        name: '综合巡查',
        id: 2
    }
])
const statusList = ref([
    {
        name: '未开始',
        id: 0
    },
    {
        name: '已开始',
        id: 1
    },
    {
        name: '已结束',
        id: 2
    }
])
const userStore = useUserStore()
const headerOdj = ref({ token: userStore.token })
const adminUrl = ref('')
adminUrl.value = import.meta.env.VITE_BASE_PATH + '/file/upload'
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const unitPage = ref(1)
const unitTotal = ref(0)
const unitPageSize = ref(10)
const dialogFormVisible = ref(false)
let validateImage = (rule, value, callback) => {
    if (!form.value.url || fileList.value.length == 0) {
        callback(new Error('请上传文件'))
    } else {
        callback()
    }
}
const rules = reactive({
    type: [{ required: true, message: '请选择巡查类型', trigger: 'change' }],
    name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
    unitIds: [{ required: true, message: '请选择巡查单位', trigger: 'change' }],
    time: [{ required: true, message: '请选择巡查时间', trigger: 'change' }],
    checkOptions: [{ required: true, message: '请选择巡查系统', trigger: 'change' }],
})

const yyglForm = ref(null)
const unitTable = ref(null)
const initForm = () => {
    yyglForm.value.resetFields()
    form.value = {
        name: '',
        type: '',
        time: [],
        start: '',
        end: '',
        checkOptions: [],
        units: '',
        unitIds: ''
    }
    unitTable.value?.clearSelection()
}

const checkedColumns = ref(['序号', '巡查类型', '任务名称', '巡查系统', '任务状态', '任务下达日期', '开始日期', '结束日期', '单位数量', '已完成数', '未完成数', '操作'])

if (localStorage.getItem('columnData') && JSON.parse(localStorage.getItem('columnData')).rwxf) {
    checkedColumns.value = JSON.parse(localStorage.getItem('columnData')).rwxf
}
const columns = ref(['序号', '巡查类型', '任务名称', '巡查系统', '任务状态', '任务下达日期', '开始日期', '结束日期', '单位数量', '已完成数', '未完成数', '操作'])
const handleColumnsChange = (val) => {
    let obj = {

    }
    if (localStorage.getItem('columnData')) {
        obj = JSON.parse(localStorage.getItem('columnData'))
    }
    obj.rwxf = val
    localStorage.setItem('columnData', JSON.stringify(obj))
}
const isEdit = ref(false)
const dialogTitle = ref('新增巡查任务')
const addUnit = () => {
    dialogTitle.value = '新增巡查任务'
    isEdit.value = false
    dialogFormVisible.value = true
}
const closeDialog = () => {
    initForm()
    dialogFormVisible.value = false
}

const handleClose = (done) => {
    initForm()
    done()
}
const handleUserClose = (done) => {
    initUserForm()
    done()
}
const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
}
const handleUnitChange = (val) => {
    unitPage.value = val
    //getTableData()
}
const tableData = ref([])
// 查询
const getTableData = async () => {
    const res = await patrolTask({
        pageNumber: page.value,
        pageSize: pageSize.value,
        ...searchInfo.value
    })
    if (res.code == 200) {
        tableData.value = res.result.data
        total.value = res.result.total
    }
}
const getUnitData = async () => {
    const res = await unitLists({
        pageNumber: unitPage.value,
        pageSize: unitPageSize.value,
        ...unitForm.value
    })
    if (res.code == 200) {
        unitData.value = res.result.data
        unitTotal.value = res.result.total
    }
}
function search() {
    unitPage.value = 1
    getUnitData()
}
function unitReset() {
    unitTable.value?.clearSelection()
    unitForm.value = {
        name: '',
        nature: ''
    }
    getUnitData()
}
function xzChange(id) {
    unitForm.value.nature = id
    getUnitData()
}
getTableData()
const qdCate = ref([
    {
        label: '统信UOS',
        value: 1
    },
    {
        label: '银河麒麟',
        value: 2
    },
    {
        label: '中标麒麟',
        value: 3
    },
    {
        label: 'Windows',
        value: 4
    }
])
const checkOptions = ref([])
const unitData = ref([])
const xzList = ref([])

onMounted(() => {
    optionList().then(res => {
        checkOptions.value = res.result
    })
    getDyList({ pageNumber: 1, pageSize: 100 }).then(res => {
        xzList.value = res.result.data.filter(item => item.type == 1)
    })
    getUnitData()
})
const unitForm = ref({
    name: '',
    nature: ''
})
const enterDialog = async () => {
    yyglForm.value.validate(async (valid) => {
        if (valid) {
            form.value.start = Date.parse(form.value.time[0]) / 1000
            form.value.end = Date.parse(form.value.time[1]) / 1000
            form.value.checkOptions = form.value.checkOptions.join(',')
            let res
            if (isEdit.value) {
                res = await taskEdit(form.value)
            } else {
                res = await taskAdd(form.value)
            }
            if (res.code == 200) {
                ElMessage({
                    type: 'success',
                    message: isEdit.value ? '编辑成功' : '添加成功!'
                })
                getTableData()
            }
            initForm()
            dialogFormVisible.value = false
        }
    })
}
const editUnit = async (row) => {
    isEdit.value = true
    dialogTitle.value = '编辑巡查任务'
    form.value = JSON.parse(JSON.stringify(row))
    form.value.time = [formatTimestamps(form.value.start), formatTimestamps(form.value.end)]
    form.value.checkOptions = form.value.checkOptions.map(item => item.id)
    form.value.unitIds = form.value.notCompleteUnit.map(item => item.unitId).join(',')
    form.value.units = form.value.notCompleteUnit.map(item => item.unitName)
    form.value.taskId = form.value.id
    dialogFormVisible.value = true
}
const delUnit = (row) => {
    ElMessageBox.confirm(
        '确认删除?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        const res = await taskDelete(row.id)
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '删除成功!'
            })
            getTableData()
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        })
    })
}
const onSubmit = () => {
    page.value = 1
    searchInfo.value.taskStart = searchInfo.value.time[0]
    searchInfo.value.taskEnd = searchInfo.value.time[1]
    getTableData()
}
const onReset = () => {
    page.value = 1
    searchInfo.value = {
        name: '',
        time: [],
        taskStart: '',
        taskEnd: '',
        taskStatus: '',
        type: ''
    }
    getTableData()
}
const dialog2 = ref(false)
function handleClose2() {
    dialog2.value = false
}
function closeDialog2() {
    dialog2.value = false
}
function confirm2() {
    dialog2.value = false
}
const selectedUnit = ref([])
function handleSelectionChange(val) {
    selectedUnit.value = val
    form.value.units = val.map(item => item.name).join(',')
    form.value.unitIds = val.map(item => item.id).join(',')
}
function openUnit() {
    dialog2.value = true
}
const unitStatusData = ref([])
const dialog3 = ref(false)
const statusTitle = ref('已完成数')
function showDialog3(row, status) {
    if (status == 1) {
        statusTitle.value = '已完成数'
        unitStatusData.value = row.completeUnit || []
    } else {
        statusTitle.value = '未完成数'
        unitStatusData.value = row.notCompleteUnit || []
    }
    dialog3.value = true
}
function handleClose3() {
    dialog3.value = false
}
function closeDialog3() {
    dialog3.value = false
}
function rowKey (row) {
  return row.id;
}
</script>

<style lang="scss">
.flex {
    .area {
        flex: 2;
        background-color: #fff;
        margin: 0.5rem 20px 0.5rem 0;
    }

    .unit {
        flex: 4;
    }
}

.ant-alert-info {
    display: flex;
    justify-content: end;
    align-items: center;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    color: #1890ff;
    padding: 5px;

    .anticon {
        display: flex;
        align-items: center;
        cursor: pointer;
    }
}

.btns {
    display: flex;
}

.section-title {
    font-weight: bold;
    font-size: 20px;
    line-height: 33px;
    padding: 8px 0 4px 14px;
    color: #4E7DFD;
    position: relative;
}

.section-title:before {
    content: '';
    position: absolute;
    top: 17px;
    left: 0;
    width: 6px;
    height: 14px;
    border-radius: 3px;
    background: #4E7DFD;
}

.tips {
    margin-bottom: 20px;
    color: #ff6666;
    margin-left: 10px;
}

.flex {
    display: flex;

    .xz-box {
        flex: 1;
        border: 1px solid #ebeef5;
        padding: 10px;

        .xz-list {
            .item {
                cursor: pointer;
                margin-bottom: 6px;
            }

            .item:hover {
                background-color: #E5EEFF;
            }
        }
    }

    .unit-box {
        flex: 2;
        margin: 0 20px;
    }

    .select-box {
        flex: 1;
        border: 1px solid #ebeef5;
        padding: 10px;
        .item{
            margin-bottom: 6px;
        }
    }
}
</style>